package com.example.myui.activity;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myui.R;
import com.example.myui.service.MyService;

public class AsyncActivity extends AppCompatActivity {

    private static final String TAG = AsyncActivity.class.getSimpleName();
    public static final String ACTION_SERVICE = "action_service";
    public static final String ACTION_THREAD = "action_thread";
    private Button start;
    private TextView progress;
    private MyAsyncTask myAsyncTask;
    private LocalBroadcastManager localBroadcastManager;
    private MyBroadcastReceiver myBroadcastReceiver;
    private TextView tvService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async);
        Log.i(TAG, "onCreate: " + Thread.currentThread().getName() + "id:" + Thread.currentThread().getId());
        initView();
        initData();
    }

    private void initData() {
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        myBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_SERVICE);
        intentFilter.addAction(ACTION_THREAD);
        localBroadcastManager.registerReceiver(myBroadcastReceiver, intentFilter);
        myAsyncTask = new MyAsyncTask();
    }

    private void initView() {
        tvService = findViewById(R.id.tv_service);
        findViewById(R.id.btn_start_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                开启服务
                Intent intent = new Intent(AsyncActivity.this, MyService.class);
                intent.putExtra("start", "start");
                startService(intent);
            }
        });

        findViewById(R.id.btn_stop_service).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                停止服务
                Intent stop = new Intent(AsyncActivity.this, MyService.class);
                stopService(stop);
            }
        });

        progress = findViewById(R.id.tv_progress);
        start = findViewById(R.id.btn_start);
        findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myAsyncTask != null && myAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
                    myAsyncTask.cancel(true);
                }
            }
        });
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (myAsyncTask.isCancelled()) {
                    Toast.makeText(AsyncActivity.this, "已经被取消了", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (myAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
                    Toast.makeText(AsyncActivity.this, "running", Toast.LENGTH_SHORT).show();
                } else {
                    myAsyncTask.execute();
                }
            }
        });
    }

    @SuppressLint("StaticFieldLeak")
    private class MyAsyncTask extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progress.setText("开始--->");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i(TAG, "onPostExecute: " + s + "isCanceled" + isCancelled());
            progress.setText(s);

        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                Log.i(TAG, "doInBackground: " + isCancelled());
                int progress = 0;
                while (progress < 20) {
                    if (isCancelled()) {
                        break;
                    }
                    Thread.sleep(500);
                    progress += 1;
                    publishProgress(progress);
                    Log.i(TAG, "doInBackground: " + progress);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            return "finished";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (isCancelled()) return;
            progress.setText(values[0] + "");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myAsyncTask != null && myAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
            myAsyncTask.cancel(true);
        }

        localBroadcastManager.unregisterReceiver(myBroadcastReceiver);
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case ACTION_SERVICE:
                    Log.i(TAG, "onReceive: " + intent.getStringExtra("service"));
                    tvService.setText(intent.getStringExtra("service"));
                    break;
                case ACTION_THREAD:
                    Log.i(TAG, "onReceive: " + intent.getStringExtra("thread"));
                    tvService.setText(intent.getStringExtra("thread"));
                    break;
            }
        }
    }
}
